﻿using BizModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Repositories;
using log4net.Config;
using log4net;

namespace AppRecruitCount
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            XmlConfigurator.ConfigureAndWatch(new FileInfo("LogConfig.xml"));

            try
            {
                var agentList = new List<Agent>();
                agentList.Add(new Agent
                {
                    AgentType = "S",
                    LinkUrl = "http://www.saramin.co.kr/zf_user/upjikjong-recruit/upjikjong-list/recruitform_type/classified/categoryCode/9%7C4/category_level/keyword/code/404/keyword_cd/40416",
                    JobType = "DEV-WEB-NET"
                });

                agentList.Add(new Agent
                {
                    AgentType = "S",
                    LinkUrl = "http://www.saramin.co.kr/zf_user/upjikjong-recruit/upjikjong-list/recruitform_type/classified/categoryCode/9%7C4/category_level/keyword/code/404/keyword_cd/40404",
                    JobType = "DEV-WEB-JAVA"
                });

                foreach (var agent in agentList)
                {
                    var param = GetRecruitInfo(agent);

                    new RecruitStateRepository().AddTodayRecruitState(param);
                }


                var logger = LogManager.GetLogger("RecAppLogger");
                LogicalThreadContext.Properties["UserId"] = "System";
                LogicalThreadContext.Properties["RefferURL"] = "";

                logger.Info(string.Format("성공적으로 {0}건의 Agent Data를 등록하였습니다.", agentList.Count));

                Console.WriteLine("성공");
            }
            catch (Exception ex)
            {
                var logger = LogManager.GetLogger("RecAppLogger");
                LogicalThreadContext.Properties["UserId"] = "System";
                LogicalThreadContext.Properties["RefferURL"] = "";

                logger.Error(ex.Message);

                Console.WriteLine("실패");
            }
        }

        private static RecruitStateT GetRecruitInfo(Agent agent)
        {
            var returnValue = new RecruitStateT();

            var request = WebRequest.Create(agent.LinkUrl);
            request.Method = "GET";

            var response = request.GetResponse();

            var dataStream = response.GetResponseStream();

            if (dataStream != null)
            {
                var reader = new StreamReader(dataStream, Encoding.GetEncoding("EUC-KR"));
                var responseHtml = reader.ReadToEnd();

                var index = responseHtml.IndexOf(@"선택하신", System.StringComparison.Ordinal);

                if (index != -1)
                {
                    var middleData = responseHtml.Substring(index, 50);

                    var strTmp = Regex.Replace(middleData, @"\D", "");
                    var nTmp = int.Parse(strTmp.Replace(",", ""));

                    returnValue.BasicDate = DateTime.Now.ToString("yyyy-MM-dd");
                    returnValue.AgentType = agent.AgentType;
                    returnValue.JobType = agent.JobType;
                    returnValue.RecruitCount = nTmp;
                    returnValue.LinkUrl = agent.LinkUrl;
                    returnValue.IsDisplay = true;
                    returnValue.InsertDate = DateTime.Now;
                    returnValue.Description = string.Empty;
                }
                else
                {
                    returnValue.BasicDate = DateTime.Now.ToString("yyyy-MM-dd");
                    returnValue.AgentType = agent.AgentType;
                    returnValue.JobType = agent.JobType;
                    returnValue.RecruitCount = -1;
                    returnValue.LinkUrl = agent.LinkUrl;
                    returnValue.IsDisplay = false;
                    returnValue.InsertDate = DateTime.Now;
                    returnValue.Description = "Html 파일에서 예상한 위치에 Recruit 정보가 없습니다.";
                }
            }
            else
            {
                returnValue.BasicDate = DateTime.Now.ToString("yyyy-MM-dd");
                returnValue.AgentType = agent.AgentType;
                returnValue.JobType = agent.JobType;
                returnValue.RecruitCount = -1;
                returnValue.LinkUrl = agent.LinkUrl;
                returnValue.IsDisplay = false;
                returnValue.InsertDate = DateTime.Now;
                returnValue.Description = "예기치 않은 이유로 FileStream 읽기 / 응답에 실패하였습니다.";
            }

            return returnValue;
        }
    }

    public class Agent
    {
        public string LinkUrl { get; set; }

        public string AgentType { get; set; }

        public string JobType { get; set; }
    }
}
